package com.flyemu.share.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.util.StrUtil;
import com.blazebit.persistence.PagedList;
import com.flyemu.share.controller.Page;
import com.flyemu.share.controller.PageResults;
import com.flyemu.share.dto.AdminDto;
import com.flyemu.share.dto.TodoListDto;
import com.flyemu.share.entity.QAdmin;
import com.flyemu.share.entity.QProject;
import com.flyemu.share.entity.QTodoList;
import com.flyemu.share.entity.TodoList;
import com.flyemu.share.enums.Priority;
import com.flyemu.share.enums.TodoState;
import com.flyemu.share.enums.TodoType;
import com.flyemu.share.repository.TodoListRepository;
import com.querydsl.core.BooleanBuilder;
import com.querydsl.core.Tuple;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;


/**
 * @功能描述: 代办项目
 * @创建时间: 2023年08月08日
 * @公司官网: www.fenxi365.com
 * @公司信息: 纷析云（杭州）科技有限公司
 * @公司介绍: 专注于财务相关软件开发, 企业会计自动化解决方案
 */
@Service
@Slf4j
@Transactional(readOnly = true)
@RequiredArgsConstructor
public class TodoListService extends AbsService {

    private final static QTodoList qTodoList = QTodoList.todoList;
    private final static QAdmin qAdmin = QAdmin.admin;
    private final static QProject qProject = QProject.project;
    private final TodoListRepository todoListRepository;

    public PageResults<TodoListDto> query(Integer merchantId, Page page, TodoListService.Query query) {
        PagedList<Tuple> fetchPage = bqf.selectFrom(qTodoList)
                .join(qAdmin).on(qTodoList.adminId.eq(qAdmin.id))
                .join(qProject).on(qTodoList.projectId.eq(qProject.id))
                .select(qTodoList, qAdmin.name,qProject.name)
                .where(query.builder.and(qTodoList.merchantId.eq(merchantId)))
                .orderBy(qTodoList.id.desc())
                .fetchJoin()
                .fetchPage(page.getOffset(), page.getOffsetEnd());
        List<TodoListDto> dtos = new ArrayList<>();
        fetchPage.forEach(tuple -> {
            TodoListDto todoListDto = BeanUtil.toBean(tuple.get(qTodoList), TodoListDto.class);
            todoListDto.setAdminName(tuple.get(qAdmin.name));
            todoListDto.setProjectName(tuple.get(qProject.name));
            dtos.add(todoListDto);
        });
        dtos.sort(Comparator.comparing(TodoListDto::getId).reversed());
        return new PageResults<>(dtos, page, fetchPage.getTotalSize());
    }

    @Transactional
    public TodoList save(TodoList todoList) {
        if (todoList.getId() != null) {
            //更新
            TodoList original = todoListRepository.getById(todoList.getId());
            BeanUtil.copyProperties(todoList, original, CopyOptions.create().ignoreNullValue());
            return todoListRepository.save(original);
        }

        return todoListRepository.save(todoList);
    }

   
    @Transactional
    public void delete(Integer todoListId, Integer merchantId) {
        jqf.delete(qTodoList)
                .where(qTodoList.id.eq(todoListId).and(qTodoList.merchantId.eq(merchantId)))
                .execute();
    }

    public static class Query {
        public final BooleanBuilder builder = new BooleanBuilder();

        public void setMerchantId(Integer merchantId) {
            if (merchantId != null) {
                builder.and(qTodoList.merchantId.eq(merchantId));
            }
        }

        public void setName(String name) {
            if (StrUtil.isNotEmpty(name)) {
                builder.and(qTodoList.name.contains(name));
            }
        }

        public void setTodoType(TodoType todoType) {
            if (todoType!=null) {
                builder.and(qTodoList.todoType.eq(todoType));
            }
        }

        public void setTodoState(TodoState todoState) {
            if (todoState!=null) {
                builder.and(qTodoList.todoState.eq(todoState));
            }
        }

        public void setPriority(Priority priority) {
            if (priority!=null) {
                builder.and(qTodoList.priority.eq(priority));
            }
        }

        public void setAdminId(Integer adminId) {
            if (adminId!=null) {
                builder.and(qTodoList.adminId.eq(adminId));
            }
        }

        public void setProjectId(Integer projectId) {
            if (projectId!=null) {
                builder.and(qTodoList.projectId.eq(projectId));
            }
        }
    }
}
